/**
 * 规则输出
 */
define(['../../model/lines/oneYAxis','../../model/lines/twoYAxis','../../model/lines/threeYAxis','../../model/lines/fourYAxis',
    '../../common/service','systemPage'],
    function(oneYAxis, twoYAxis,threeYAxis,fourYAxis,http, page) {
    var RuleScriptResult = {
        pSize : 1,
        init : function(){
            var _this = this;
            //初始化tab
            $("div.ndp-tab-wrapper[name=plain-tab]").tabs({
                list:[I18N.getText("rulescriptList","roleListTitle"),
                    I18N.getText("rulescriptResult","ruleResult"),
                    I18N.getText("optRecords","optRecords"),
                    I18N.getText("rulescriptSetting","setting")]
            }).on("TAB_CHANGE",function(e){//点击其中的一个tab发生事件
                var href = "";
                switch (e.originalEvent.data.index){
                    case 0:
                        href = "#!rulescriptList";
                        break;
                    case 1:
                        href = "#!rulescriptResult";
                        break;
                    case 2:
                        href = "#!optRecords";
                        break;
                    case 3:
                        href = "#!rulescriptSetting";
                        break;
                }
                window.location.hash = href;
            }).val(1);//设置选中的tab 索引，默认0;

            //加载产品与配置
            _this.initZtreeToAppsAndConfigurations();
            //绑定事件
            _this.bindEvent();
            //页面初始加载 查询分组信息
            _this.queryGroup();
        },
        bindEvent : function(){
            var _this = this;
            //点击账号事件
            $('#accountBtn').off('click').on('click', function () {
                if($('#accountMenu .selectdNode').length==0){
                    Kit.alert2(I18N.getText('rulescriptResult','choseAppOrPlatform'));
                    return false;
                }
            });

            //点击查询事件
            $("#search-action").off('click').on('click',function(){
                //校验
                var sortMix = $('#sortMix').val();
                if ((!_.isEmpty(sortMix)) && _this.valicateNumber($('#sortMix'))) {
                    return;
                }

                var sortMax = $('#sortMax').val();
                if ((!_.isEmpty(sortMax)) && _this.valicateNumber($('#sortMax'))) {
                    return;
                }

                //先查分组
                _this.queryGroup();
            });

            //点击清除事件
            $('#clean-all-acation').off('click').on('click', function(){
                _this.cleanAllSnap();
            });

            //根据Tab查询相应的规则输出结果
            $('#group-tabs').on('shown.bs.tab', 'a[data-toggle="tab"]', function(){
                _this.cPage = 1;
                _this.queryRuleResults();
            });

            //修改预算、出价事件
            $('#group-tab-contents').on('click', '.edit', $.proxy(_this.editValue, _this));

            //预算、出价 失去焦点事件
            $('#group-tab-contents').on('focusout', '.edit-input', $.proxy(_this.modifyFocusout, _this));

            //提交优化事件
            $('#group-tab-contents').on('click', '.btn-optimize', $.proxy(_this.openOptimizeDialog, _this));

            //点击表头隐藏ad 信息
            $('#group-tab-contents').on('click', '.toggle-thead', function(){
                $(this).parents('table').find('tbody').toggle();
            });
        },
        initZtreeToAppsAndConfigurations: function () {
            var _this = this;

            //查询应用及配置
            queryAllApps(function (result) {
                var _appTree = {};
                var configuration;
                var nodes = [],
                    parent = {},
                    node = {};
                parent = {
                    id: "0",
                    pId: '0',
                    fbConnectionObjectId: 0,
                    name: I18N.getText('rulescriptResult','allAppPlatform'),
                    isParent: true
                };
                nodes.push(parent);
                _appTree[0] = nodes;
                $.each(result, function (i, d) {
                    nodes = [];
                    parent = {
                        id: "p-" + d.id,
                        pId: '',
                        fbConnectionObjectId: d.fbConnectionObjectId,
                        name: d.name,
                        icon: d.picture,
                        isParent: true
                    };
                    nodes.push(parent);
                    configuration = d.configurations;
                    for (var i = 0; i < configuration.length; i++) {
                        node = {
                            id: configuration[i].id,
                            pId: "p-" + d.id,
                            name: configuration[i].platform,
                            icon: "./imgs/icon-market.png",
                            objectStoreUrl: configuration[i].objectStoreUrl,
                            realName: configuration[i].platform
                        };
                        nodes = nodes.concat(node);
                    }
                    _appTree[d.id] = nodes;
                });
                //动态写入
                var zNodes = [];
                $("#tree").html("<ul id='treeView' class='ztree' ></ul>");
                $.each(_appTree, function (i, d) {
                    if (d !== null) {
                        $.each(d, function (i2, d2) {
                            zNodes.push(d2);
                        });
                    }
                });
                _this.initAppTree($("#treeView"), zNodes);
            })

            function queryAllApps(callback) {
                http.work("/connectionobjects/searchAppsAndConfigurations",{},"POST").then(function(rsp) {
                    var data = rsp.data;
                    if (!data || data.length == 0) {
                        return false;
                    }
                    data = _.sortBy(data, function (item) {
                        return item.name.toLowerCase();
                    });
                    callback(data);
                });
            }

        },
        initAppTree : function(_dom, _zNodes){
            var _this = this;

            //参数配置
            var setting = {
                view: {
                    dblClickExpand: false,
                    showLine: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeExpand: beforeExpand,
                    onExpand: onExpand,
                    onCollapse: onCollapse,
                    onClick: onClick
                }
            };

            var curExpandNode = null;
            //用于捕获父节点展开之前的事件回调函数，并且根据返回值确定是否允许展开操作
            function beforeExpand(treeId, treeNode) {
                var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
                var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
                var zTree = $.fn.zTree.getZTreeObj("treeView");
                for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
                    if (treeNode !== treeNodeP.children[i]) {
                        zTree.expandNode(treeNodeP.children[i], false);
                    }
                }
                while (pNode) {
                    if (pNode === treeNode) {
                        break;
                    }
                    pNode = pNode.getParentNode();
                }
                if (!pNode) {
                    singlePath(treeNode);
                }

            }

            function singlePath(newNode) {
                if (newNode === curExpandNode) return;
                if (curExpandNode && curExpandNode.open == true) {
                    var zTree = $.fn.zTree.getZTreeObj("treeView");
                    if (newNode.parentTId === curExpandNode.parentTId) {
                        zTree.expandNode(curExpandNode, false);
                    } else {
                        var newParents = [];
                        while (newNode) {
                            newNode = newNode.getParentNode();
                            if (newNode === curExpandNode) {
                                newParents = null;
                                break;
                            } else if (newNode) {
                                newParents.push(newNode);
                            }
                        }
                        if (newParents != null) {
                            var oldNode = curExpandNode;
                            var oldParents = [];
                            while (oldNode) {
                                oldNode = oldNode.getParentNode();
                                if (oldNode) {
                                    oldParents.push(oldNode);
                                }
                            }
                            if (newParents.length > 0) {
                                zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                            } else {
                                zTree.expandNode(oldParents[oldParents.length - 1], false);
                            }
                        }
                    }
                }
                curExpandNode = newNode;
            }

            //用于捕获节点被展开的事件回调函数
            function onExpand(event, treeId, treeNode) {
                curExpandNode = treeNode;
            }

            //用于捕获节点折叠的事件回调函数
            function onCollapse() {
            }

            //用于捕获节点被点击的事件回调函数,切换不同的应用会查询该应用对应的账号列表
            function onClick(e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("treeView");
                zTree.expandNode(treeNode, null, null, null, true);
                var parentNode = treeNode.getParentNode();
                var tmpHtml = '';
                var newfbConnectionObjectId;
                var platform = "";
                if (parentNode) {
                    //选择产品配置
                    tmpHtml = "<img style='margin:0 5px;' src='" + parentNode.icon + "' />"
                        +"<strong>"
                        + parentNode.name
                        + "</strong> / "
                        + treeNode.name;
                    newfbConnectionObjectId = parentNode.fbConnectionObjectId;
                    platform = treeNode.name;
                } else {
                    //选择应用
                    if(typeof treeNode.icon != "undefined"){
                        tmpHtml = "<img style='margin:0 5px;' src='" + treeNode.icon + "' />"
                            + "<strong>"
                            + treeNode.name
                            + "</strong>";
                    }else{
                        tmpHtml =  "<strong>"
                            + treeNode.name
                            + "</strong>";
                    }
                    newfbConnectionObjectId = treeNode.fbConnectionObjectId;
                }
                $("#platformDiv").val(platform);
                var oldfbConnectionObjectId = $("#fbConnectionObjectId").val();

                if (oldfbConnectionObjectId != newfbConnectionObjectId) {
                    _this.appId = newfbConnectionObjectId;
                    //当切换到新的应用
                    $("#fbConnectionObjectId").val(newfbConnectionObjectId);
                    //根据账号查询应用
                    $("#account-list-title").addClass('hide');
                    if(newfbConnectionObjectId == 0){
                        $('#accountMenu').empty();
                        //显示选中内容
                        $("#result").html(tmpHtml).data("node", treeNode);
                        //隐藏下拉树
                        $("#tree").addClass("hide");
                        $("#result").removeClass("choose_active");
                        return false;
                    }
                    var par = {
                        connObjId: newfbConnectionObjectId
                    };
                    http.work('/entrustaccounts/getAccounts',par,'POST').then(function(res){
                        var accountHtml = '';
                        var isFirst = true;
                        var _role = {};
                        var data = res.data;
                        if(!data.accounts || data.accounts.length == 0){
                            Kit.alert2(I18N.getText('rulescriptResult','actNotFoundMsg'));
                            $("#account-list").html('');
                            return false;
                        }
                        data.accounts = _.sortBy(data.accounts, function (item) {
                            return item.timezone.toLowerCase();
                        });

                        $.each(data.accounts, function(i, account){
                            accountHtml += '<div class="col-sm-3 isShowAccount" style="min-height: 25px;" title="'+account.displayName+'">'+account.displayName+'</div>';
                            isFirst = false;
                            _role[account.fbAccountId] = account.role;
                        });

                        $("#account-list").data('role', _role);
                        $("#account-list").html(accountHtml);
                        accountTree(data.accounts);
                        _this.dataAccounts = data.accounts;
                    });
                }

                //显示选中内容
                $("#result").html(tmpHtml).data("node", treeNode);
                //隐藏下拉树
                $("#tree").addClass("hide");
                $("#result").removeClass("choose_active");
                //获取批次信息，并渲染至DOM
                //  loadPublishBatch(treeNode.id);
            }

            /**
             * 账号tree列表
             */
            function accountTree(accountList) {
                var self = this;
                var moreTagrtings = new Array();
                $.each(accountList, function (i, v) {
                    moreTagrtings.push({
                        id: v.fbAccountId,
                        name: v.displayName + "  (" + (v.timezone ? v.timezone : "") +"  )"
                    });
                });

                //初始化 高级定位 树状结构
                var moreTagrtingsElement = '';
                $.each(moreTagrtings, function (i, v) {
                    moreTagrtingsElement += '<li>';
                    if (v.children) {
                        //父
                        moreTagrtingsElement += '<a id="targetingParent" href="javascript:void(0);" style="padding-left: 8px;">'
                            + '<span id="icon" class="fa fa-caret-right" style="padding-right: 3px;"></span><span>' + v.name + '</span>'
//                            + '<span class="fa fa-check pull-right hide" style="margin-right: 1px;"></span>'
                            + '</a>';
                        //子
                        moreTagrtingsElement += '<ul id="targetingChildren" class="dropdown-list-submenu hide">';
                        $.each(v.children, function (index, child) {
                            moreTagrtingsElement += '<li class="selectdNode" selectd-node="' + child.id + '" checked="checked">';
                            moreTagrtingsElement += '<a href="javascript:void(0);"><span>' + child.name + '</span><span id="selectIcon" class="fa fa-check pull-right " style="margin-right: 20px;"></span></a>';
                            moreTagrtingsElement += '</li>';
                            $('#settingCtn').append('<div ctn="' + child.id + '" step-title="' + child.name + '" class="form-group" style="display:none;" ></div>');
                        });
                        moreTagrtingsElement += '</ul>';
                    } else {
                        moreTagrtingsElement += '<li class="selectdNode" selectd-node="' + v.id + '" checked="checked">';
                        moreTagrtingsElement += '<a href="javascript:void(0);"><span>' + v.name + '</span><span id="selectIcon" class="fa fa-check pull-right " style="margin-right: 1px;"></span></a>';
                        moreTagrtingsElement += '</li>';
                        $('#settingCtn').append('<div ctn="' + v.id + '" step-title="' + v.name + '" class="form-group" style="display:none;" ></div>');
                    }
                });
                moreTagrtingsElement += "</li>";
                $('#accountMenu').html(moreTagrtingsElement);

                //勾选事件 控制显示与否
                $('#accountMenu .selectdNode').on('click', function () {
                    var btn = $(this);
                    var ctn = $('div[ctn=' + btn.attr('selectd-node') + ']');
                    var selectIcon = $(this).find("#selectIcon");
                    selectIcon.toggleClass("hide");
                    if (selectIcon.hasClass("hide")) {
                        btn.removeAttr('checked')
                        ctn.hide();
                    } else {
                        btn.attr('checked', 'checked')
                        ctn.show();
                    }
                    $('#accountMenu').trigger('clickAccount');
                    return false;
                });
            }

            //显示为树
            $.fn.zTree.init($("#treeView"), setting, _zNodes);

            $("body").off("click").on("click", function(e){
                var _e = $(e.target);
                if (_e.hasClass("app-select2") || _e.parents(".app-select2").length > 0){
                    $("#result").toggleClass("choose_active");
                    $("#tree").toggleClass("hide");
                } else if (_e.parents(".tree-ratus").length > 0){
                    return false;
                } else {
                    $("#tree").addClass("hide");
                }
            });
        },
        /**
         * [function 查询 group list] 即Tab页组
         * @return {[type]} [description]
         */
        queryGroup: function() {
            var _this = this;
            //清空分页信息
            $(".pagination").empty();

            //构造参数
            var params = {
                appId: _this.appId,
                iswatch: $('[name="adgroup-status"]').val()  || 'false'
            };
            //账号
            var fbAccountIds = [];
            $('#accountMenu li[checked]').each(function() {
                fbAccountIds.push($(this).attr('selectd-node'));
            });
            params.fbAccountIds = fbAccountIds.join(',');

            var loadingArea = $(".container-fluid")
            Kit.loading.show(loadingArea);
            http.work('/ruleresult/grouplist',params,'POST').then(function(res){
            	if(res.flag == 'success'){
	                setTimeout(function() {
	                    _this.renderGroupTabs(res.data);
	                }, 50);
            	}
                Kit.loading.hide(loadingArea);
            });
        },
        /**
         * [renderGroupTabs 渲染 group tab]
         * @param  {[type]} groups [description]
         * @return {[type]}        [description]
         */
        renderGroupTabs: function(groups) {
            var html = _.template($('#t-group-tabs-li').text())({groups: groups});
            $('#group-tabs').html(html);
            $('#group-tabs').find('a:first').tab('show');
            if (groups.length == 0) {
                $(".page-info").addClass("hide");
                $("#group-tabs").addClass("hide");
                $('#group-tab-contents').html(I18N.getText('rulescriptResult','nothingFound'));
            } else {
                $(".page-info").removeClass("hide");
                $("#group-tabs").removeClass("hide");
            }
        },
        queryRuleResults: function( _cPage_ ) {
            var _this = this;
            //构造参数
            var target = $('#group-tabs').find('.active a');
            _this.groupId = target.data('group-id'); // 分组
            _this.iswatch = $('[name="adgroup-status"]').val() + '';
            var params = {
                group: _this.groupId,
                iswatch: _this.iswatch,
                cPage: _cPage_ || _this.cPage,
                pSize: _this.pSize,
                sortMix : $('#sortMix').val(),
                sortMax : $('#sortMax').val()
            };

            var _fbConnectionObjectId = $("#fbConnectionObjectId").val();
            if (_this.appId) {
                params.fbConnectionObjectId = _this.appId;
            }
            var fbAccountIds = [];
            $('#accountMenu li[checked]').each(function() {
                fbAccountIds.push($(this).attr('selectd-node'));
            });
            params.fbAccountIds = fbAccountIds.join(',');
            params.platform = $("#platformDiv").val();

            //遮罩
            var loadingArea = $('#group-tab-contents');
            typeof( _cPage_ ) == 'undefined' ? Kit.loading.show(loadingArea) : '';
            http.work('/ruleresult/ruleResultList', params, 'POST').then(function(res){
                var data = res.data;
                //如果当前页大于总页数 且不为预加载时  且当前不是第一条时
                if(data.paginator.cPage > data.paginator.tSize && typeof( _cPage_ ) == 'undefined' && _this.cPage != 1){
                    _this.cPage = Number(_this.cPage - 1);
                    _this.queryRuleResults();
                }else if( typeof( _cPage_ ) != 'undefined' ){
                    //预加载设为缓存
                    _this.setCache(data);
                }else{
                    //非预加载 需要立刻渲染
                    Kit.loading.hide(loadingArea);
                    _this.resetHtmlForData(data);
                }
            });
        },
        /*
         @数据预加载
         $.data:需要存储的数据
        */
        setCache: function(data){
            var _this = this;
            //如果数据返回为空，则立刻返回
            if(!data.ruleresult || data.ruleresult.length == 0){
                return false;
            }
            if( Number(_this.cPage) + 1 == data.paginator.cPage){
                console.log('setnextData');
                _this.nextData = data;
            }else if( Number(_this.cPage) - 1 == data.paginator.cPage ){
                console.log('setprevData');
                _this.prevData = data;
            }
        },
        /*
         @通过查询获得数据进行 HTML重置
         */
        resetHtmlForData: function( data ){
            var _this = this;
            //清空Tab页内容
            $("#group-tab-contents").empty();

            if (data.ruleresult && data.ruleresult.length == 0 ) {
                $('#group-tab-contents').html(I18N.getText('rulescriptResult','nothingFound'));
                //当查询结果为空 则隐藏分页信息
                $('.page-info').hide();
                return false;
            }

            //重新渲染 分页组件
            _this.renderPageInfo(data.paginator);

            _this.adSetData = data.ruleresult[0]; //取第一个
            _this.adSetData.budget = Number(_this.adSetData.budget / 100).toFixed(2); //处理精度
            //处理bidType
            if (_this.adSetData.bidType && _this.adSetData.bidType.indexOf('_') > -1) {
                var bidTypeArr = _this.adSetData.bidType.split('_');
                if (bidTypeArr.length > 1) {
                    _this.adSetData.bidType = bidTypeArr[1];
                }
            }

            //渲染Tab页内容
            _this.renderGroupTabContents(data.ruleresult);
            //查询建议出价
            _this.queryOfferBid(_this.adSetData.adsetId);


            //数据预加载  -> 获取下一页数据
            if( data.paginator.tPage > data.paginator.cPage ){
                _this.queryRuleResults( Number(_this.cPage) + 1 );
            }
            //数据预加载  -> 获取上一页数据
            if( data.paginator.cPage > 1 ){
                _this.queryRuleResults( Number(_this.cPage) - 1 );
            }

            //图形处理
            if (!typeof data.ruleresult[0].chart ||  typeof data.ruleresult[0].chart == '') {
                return;
            }
            $("#group-tab-contents tbody").each(function(i) {
                var $tbody = this;
                var chartObj = {};
                if (i == 0) {
                    //adset chart
                    chartObj = JSON.parse(data.ruleresult[0].chart);
                    if (chartObj.length < 1) {
                        console.log("没有图形数据");
                        return;
                    }
                    //adset only one data
                    _this.bindChartEvent($(this).find("tr"), chartObj);
                } else if (i == 1) {
                    // ad  Loss
                    var adList = data.ruleresult[0].adBlockResults[0].adGroupResultVos;
                    $.each(adList, function(j) {
                        if (typeof adList[j].chart != "undefined") {
                            chartObj = JSON.parse(adList[j].chart);
                            _this.bindChartEvent($($tbody).find("tr")[j], chartObj);
                        }
                    });
                } else {
                    // i = 2  ad normal
                    var adList = data.ruleresult[0].adBlockResults[1].adGroupResultVos;
                    $.each(adList, function(j) {
                        if (typeof adList[j].chart != "undefined") {
                            chartObj = JSON.parse(adList[j].chart);
                            _this.bindChartEvent($($tbody).find("tr")[j], chartObj);
                        }
                    });
                }
            });
        },
        renderPageInfo: function(_paginator) {
            var _this = this;
            page.init(_paginator, {}, $('.container-fluid'), function(_query_) {
                _this.dialogQueryRuleResults( _query_); //进行对话验证
            });
            $('.page-info').show();
        },
        /**
         * { 在翻页的时候,如果有数据变更则弹出对话框 }
         * $._query_: 分页回调函数返回的 分页数据
         * @method     dialogQueryRuleResults
         */
        dialogQueryRuleResults: function( _query_ ) {
            var _this = this;
            var params = _this.getDialogParams();
            var isModify = false;
            if ((params.ads.length > 0)
                || (params.budgetNew != params.budgetOld)
                || (params.oldStatus != params.status)
                || (params.vpiNew != params.vpiOld)) {
                isModify = true;
            };

            if (isModify) {
                var _pageModifyModal = $('#page-modify-modal');
                _pageModifyModal.modal({
                    backdrop: 'static',
                    keyboard: false
                });
                //返回修改事件
                _pageModifyModal.find(".modify-btn").off("click").on("click", function(){
                    _pageModifyModal.modal("hide");
                });
                //继续翻页事件
                _pageModifyModal.find(".continue-btn").off("click").on("click", function(){
                    _pageModifyModal.modal("hide");
                    _this.verifyCache( _query_.cPage );
                });

                _pageModifyModal.find(".page-modify-area").html( _.template($('#t-modify-data').text())(params));
               //去除删除标志
                _pageModifyModal.find(".page-modify-area").find('.fa-trash-o').each(function() {
                    $(this).parent().parent().remove();
                });
                _pageModifyModal.modal("show");
            } else {
                _this.verifyCache( _query_.cPage );
            }
        },
        /*
         @在调用queryRuleResults前 判断该条数据是否已经预加载
         存在：直接渲染
         不存在：调用获取数据
         */
        verifyCache: function(_cPage_){
            var _this = this;
            _this.cPage = _cPage_;
            //nextData
            console.log(_this.cPage )
            if( _this.nextData && _this.nextData.paginator.cPage == _this.cPage ){
                console.log('nextData');
                _this.resetHtmlForData( _this.nextData );
                //prevData
            }else if( _this.prevData && _this.prevData.paginator.cPage == _this.cPage ){
                console.log('prevData');
                _this.resetHtmlForData( _this.prevData );
                //Kit.loading
            }else{
                console.log('Kit.loading');
                _this.queryRuleResults();
            }
        },
        /**
         * [renderGroupTabContents 渲染 group content]
         * @param  {[type]} results [description]
         * @return {[type]}         [description]
         */
        renderGroupTabContents: function(_ruleresults) {
            var _this = this;
            $.each(_ruleresults, function(i, _result){
                // 计算CPI
                var totalCost = (_result.costSum).replace('$','');
                totalCost = Number(totalCost);
                if (!isNaN(totalCost) && _result.resultsSum * 1>0){
                    _result.LeftTimeCPI =  '$'+ (totalCost / _result.resultsSum).toFixed(2)
                } else {
                    _result.LeftTimeCPI = '- -';
                }

                $('#group-tab-contents').append(_.template($('#t-group-tab-content').text())(_result));
                var _tabContent = $("#ruleresult-" + _result.adsetId);

                //渲染Adset区域
                var _adsetObj = {
                    name : _result.name,
                    status :　_result.status,
                    adsetId : _result.adsetId,
                    budget : _result.budget,
                    budgetType : _result.budgetType,
                    bidType : _result.bidType
                };

                //计算统计数据部分的表头 表体
                _adsetObj.ths = _this.getThs(_result.sortCol);
                _adsetObj.contents = _this.getTBodys(_result.sortCol, _result.extendValue, _result.stat);

                //解析 出价
                //TODO  本次迁移仅仅满足员功能 需要兼容2.4的出价体系
                var _bidObject = {}
                var _bid = _result.bid;
                if (_bid && _bid != ''){
                    _bid = _bid + '';
                    if (_bid.indexOf('{') >= 0) {
                        // 如果是Json对象需要解析
                        var _bidInfo = JSON.parse(_bid);
                        if (jQuery.isEmptyObject(_bidInfo)){
                            //空Json对象 则认为是无效的出价
                            _bidObject.valid = false;
                        } else {
                            _bidObject.valid = true;
                            for (key in _bidInfo) {
                                _bidObject.bidKey = key;
                                _bidObject.bidValue = _bidInfo[key];
                                _bidObject.showBidValue = Number(_bidInfo[key] / 100).toFixed(2);
                            }
                        }
                    } else {
                        // 不解析 直接展示
                        _bidObject.bidKey = '';
                        _bidObject.valid = true;
                        _bidObject.bidValue = _bid;
                        _bidObject.showBidValue = _bid;
                    }
                } else {
                    //无效的出价
                    _bidObject.valid = false;
                }
                _adsetObj.bidObject = _bidObject;
                _tabContent.find(".adset-area").html(_.template($('#adset-table').text())(_adsetObj));


                //渲染广告块
                var blockTables = '';
                if (_result.adBlockResults){
                    var _showAdBlockResult;
                    $.each(_result.adBlockResults, function(blockIndex, _adBlockResult){
                        _showAdBlockResult = {
                            tableTrBaseline : '',
                            group : _adBlockResult.group,
                            fold : _adBlockResult.fold,
                            adGroupResults : []
                        };
                        if(_adBlockResult.baseline && _adBlockResult.baseline.length > 0){
                            _showAdBlockResult.tableTrBaseline='table-tr-baseline';
                        }

                        //动态表头
                        _showAdBlockResult.ths = _this.getThs(_adBlockResult.sortCol);

                        // adGroup信息
                        if (_adBlockResult.adGroupResultVos){
                            $.each(_adBlockResult.adGroupResultVos, function(adGroupIndex, _adGroupResult){
                                _adGroupResult.contents = _this.getTBodys(_adBlockResult.sortCol, _adGroupResult.extendValue, _adGroupResult.statResult);
                                _showAdBlockResult.adGroupResults.push(_adGroupResult);
                            })
                        }

                        blockTables +=  _.template($('#ad-block-table').text())(_showAdBlockResult);
                    })
                }
                _result.blockTables = blockTables;
                _tabContent.find(".ad-block-area").html(blockTables);

                //渲染统计时间区域
                var timeObj = {
                    alarmTime : moment(_result.alarmTime).format('YYYY-MM-DD HH:mm:ss'),
                    watchTime : moment(_result.watchTime).format('YYYY-MM-DD HH:mm:ss'),
                    optimizeTime : moment(_result.optimizeTime).format('YYYY-MM-DD HH:mm:ss'),
                    dataRefreshTime : moment(_result.dataRefreshTime).format('YYYY-MM-DD HH:mm:ss'),
                    watchLength : _result.watchLength,
                    watchSpend : _result.watchSpend,
                    consumeSpend : _result.consumeSpend,
                    delayWatchHours : moment(_result.dataRefreshTime).diff(moment(_result.optimizeTime),'hours'),
                    isWatch: _result.isWatch
                }
                _tabContent.find(".time-area").html(_.template($('#time-area').text())(timeObj));

            });

            $('span').tooltip();
        },
        getThs : function(_sortCols){
            var title = ''
            var ths = [];
            $.each(_sortCols, function(i, _col){
                colTitle = _col.toLowerCase();
                switch (colTitle){
                    case 'clicks' :
                        title = I18N.getText('rulescriptResult','clicks');
                        break;
                    case 'impressions' :
                        title = I18N.getText('rulescriptResult','impressions');
                        break;
                    case 'results' :
                        title = I18N.getText('rulescriptResult','results');
                        break;
                    case 'socialclicks' :
                        title = I18N.getText('rulescriptResult','socialclicks');
                        break;
                    case 'socialimpressions' :
                        title = I18N.getText('rulescriptResult','socialimpressions');
                        break;
                    case 'socialspent' :
                        title = I18N.getText('rulescriptResult','socialspent');
                        break;
                    case 'socialuniqueclicks' :
                        title = I18N.getText('rulescriptResult','socialuniqueclicks');
                        break;
                    case 'socialuniqueimpressions' :
                        title = I18N.getText('rulescriptResult','socialuniqueimpressions');
                        break;
                    case 'spent' :
                        title = I18N.getText('rulescriptResult','spentLabel');
                        break;
                    case 'uniqueclicks' :
                        title = I18N.getText('rulescriptResult','uniqueclicks');
                        break;
                    case 'uniqueimpressions' :
                        title = I18N.getText('rulescriptResult','uniqueimpressions');
                        break;
                    case 'loss' :
                        title = I18N.getText('rulescriptResult','loss');
                        break;
                    case 'cost' :
                        title = I18N.getText('rulescriptResult','cost');
                        break;
                    case 'roi' :
                        title = I18N.getText('rulescriptResult','roi');
                        break;
                    default:
                        title = _col;
                }
                ths.push(title)
            });

            return ths;
        },
        getTBodys : function (_sortCols, _extendValue, _stas){
            var contents = [];
            var _colVals;
            $.each(_sortCols, function(i, _col) {
                //跟据列头 获取相应的value
                var _colVal = '';
                if (_extendValue) {
                    _colVal = undefined == _extendValue[_col] ? '' : _extendValue[_col] + '';
                }

                if (_colVal == '') {
                    //不是扩展值则是基础统计值
                    if (_stas) {
                        _colVal = undefined == _stas[_col] ? '' : _stas[_col] + '';
                    }
                }

                if (_colVal != '') {
                    _colVals = (_colVal).split('/')
                } else {
                    _colVals = []
                }
                contents.push(_colVals)
            });

            return contents;
        },
        /**
         * [queryOfferBid 获取到建议出价]
         * @return {[type]} [description]
         */
        queryOfferBid: function(_adsetId) {
            var _this = this;
            var params = {
                adSetId: _adsetId
            }
            http.work('/ruleresult/queryOfferBid',params,'POST').then(function(res){
                var data = res.data;
                if (data.offerbid) {
                    $('#offerbid').html('<strong>' + data.offerbid + '</strong>');
                }
            });
        },
        bindChartEvent: function(obj, chartObj) {
            var _this = this;
            $(obj).click(function(e) {
                if ($(e.target).hasClass("no-chart") || $(e.target).parents(".no-chart").length > 0){
                    return;
                }
                if ($(this).next("#ad-chart-row").get(0)) {
                    //已渲染
                    $("#ad-chart-row").remove();
                    return;
                } else {
                    $("#ad-chart-row").remove();
                }

                //初始化select
                var selectDiv = "<div class='chart-select'><select class='form-control'>";
                $(chartObj).each(function(i) {
                    selectDiv += "<option value=" + chartObj[i].selectName + ">" + chartObj[i].selectName + "</option>";
                });
                selectDiv += "</select></div>";
                var colNum = $(this).find("td:visible").length;
                var addHtml = "<tr id='ad-chart-row'><td class='chartTd' colspan='" + colNum + "'>" +
                    "<div>" + selectDiv + "<div id='ad-chart-id'/></div>";
                $(this).after(addHtml);
                //绑定数据
                $(chartObj).each(function(i) {
                    $(".chart-select select").data(chartObj[i].selectName, chartObj[i]);
                });
                //处理图形数据
                _this.initChartData(chartObj[0], "ad-chart-id");

                //绑定select事件。
                $(".chart-select select").change(function() {
                    _this.initChartData($(this).data($(this).val()), "ad-chart-id");
                });
            });
        },
        initChartData: function(data, domId) {
            var _this = this;
            var _json = _this.getLineData(data.lineType);
            _json.data[0].fields = data.fields;
            _json.data[0].rows = data.rows;
            if (typeof data.selectName == "undefined") {
                _json.titles[0].label.content = "";
            } else {
                _json.titles[0].label.content = data.selectName;
            }
            //设置阈值线  默认将要设置阈值的线放在第一位
            if (typeof data.lineScale == 'undefined') {
                //移除CPI阈值线
                json.grammar.coordinates.dimensions[0].axis[2].lineGuides = [];
                json.grammar.coordinates.dimensions[0].axis[2].scale = {};
                console.log('not line guides');
            } else {
                _json.grammar.coordinates.dimensions[0].axis[2].lineGuides[0].value = data.lineScale.value;
                _json.grammar.coordinates.dimensions[0].axis[2].lineGuides[0].label = data.lineScale.label;
                if (typeof data.lineScale.max != "undefined") {
                    _json.grammar.coordinates.dimensions[0].axis[2].scale.spans.max = data.lineScale.max;
                }
            }
            var chartWidget = new ChartWidget();
            var eventListener = new ChartEventListener();
            chartWidget.addEventListener(eventListener);
            chartWidget.placeAt($('#' + domId)[0]);
            chartWidget.setVisJson(_json);
        },
        getLineData: function(lineType) {
            var data;
            if (lineType == 1) {
                data = oneYAxis;
            } else if (lineType == 2) {
                data = twoYAxis;
            } else if (lineType == 3) {
                data = threeYAxis;
            } else if (lineType == 4) {
                data = fourYAxis;
            }
            return data;
        },
        /**
         * [getDialogParams 得到向确认对话框中使用的参数]
         * @return {[type]} [description]
         */
        getDialogParams: function() {
            var _this = this;
            var ads = [];

            //遍历AdGroup状态
            $('.ad-group-status').each(function(i, v) {
                var adGroupId = $(this).data('adgroup-id');
                var status = $(this).is(':checked') ? 'ACTIVE' : 'PAUSED';
                var name = $(this).data('adgroup-name');
                var oldStatus = $(this).data('original-value');
                var mappingStatus = $(this).data('original-mapping-value');
                if (status !== mappingStatus) {
                    ads.push({
                        adGroupId: adGroupId,
                        status: status,
                        name: name,
                        oldStatus: oldStatus,
                        mappingStatus: mappingStatus
                    });
                }
            });
            var inputBid = $('.input-bid');
            var vpiOldKey = inputBid.data('bid-key');
            var vpiOld = inputBid.data('original-value') + '';
            var vpiNew = inputBid.val() + '';
            var params = {
                id: _this.adSetData.id,
                adSetId: _this.adSetData.adsetId,
                ruleId:_this.adSetData.ruleId,
                fbAccountId: _this.adSetData.fbAccountId,
                budgetType: _this.adSetData.budgetType,
                budgetOld: (_this.adSetData.budget + ''),
                budgetNew: ($('.input-budget').val() + ''),
                vpiOldKey: vpiOldKey,
                vpiOld: vpiOld,
                vpiNew: vpiNew,
                ads: ads,
                name: $('.adset-status').data('adset-name')
            };
            if ($('.adset-status').length > 0) {
                params.status = ($('.adset-status:checked').is(':checked') ? 'ACTIVE' : 'PAUSED');
                params.mappingStatus = $('.adset-status').data('original-mapping-value');
                params.oldStatus = $('.adset-status').data('original-value');
            }
            return params;
        },
        /**
         * [openOptimizeDialog 打开确认优化的dialog]
         * @return {[type]}             [description]
         */
        openOptimizeDialog: function() {
            var _this = this;

            var optimizeConfirmModal= $('#optimize-confirm-modal');
            optimizeConfirmModal.modal({
                backdrop: 'static',
                keyboard: false
            });


            //渲染修改信息
            var modifyDataHtml = _.template($('#t-modify-data').text())(_this.getDialogParams());
            $('#t-optimize-dialog-content-table').html(modifyDataHtml);
            //恢复初始状态
            $('input[name=isWatch][value="2"]').prop('checked', 'checked');
            $('input[name=delaySpent]').removeClass("anim_image_glow").val('');
            $('input[name=delayHours]').removeClass("anim_image_glow").val(24);
            optimizeConfirmModal.modal("show");

            //确认优化
            $("#confirm-btn", optimizeConfirmModal).off("click").on("click", function(){
                if ($('input[name=isWatch]:checked').val() == 1) {
                    //校验时间
                    if (_this.valicateNumber($('[name="delayHours"]'))) {
                        return;
                    }
                }

                if ($('input[name=isWatch]:checked').val() == 2) {
                    //花费
                    if (_this.valicateNumber($('[name="delaySpent"]'))) {
                        return;
                    }
                }

                var params = _this.getOptimizeParams();
                //self.showLoading();
                //TODO 遮罩
                http.work('/ruleresult/exeOptimize',params,'POST').then(function(res){
                    _this.prevData = undefined;
                    _this.nextData = undefined;
                    _this.verifyCache( Number(_this.cPage || 0) + 1);
                });
                optimizeConfirmModal.modal("hide");
            });

            //删除优化条件
            optimizeConfirmModal.find(".optimize-del-btn").off("click").on("click", function(e){
                $(e.target).parents('tr').remove();
            });
        },
        /**
         * [valicateNumber 验证为正整数]
         * @param  {[type]} $dom [description]
         * @return {[type]}      [description]
         */
        valicateNumber: function($dom) {
            var val = $dom.val();
            var re = /^[1-9]+[0-9]*]*$/;
            if (!re.test(val)) {
                Kit.alert2("请输入正整数");
                Kit.warning($dom)
                $dom.focus();
                return true;
            }
            return false;
        },
        /**
         * [getOptimizeParams 得到向后台请求提交的优化参数]
         * @return {[type]} [description]
         */
        getOptimizeParams: function() {
            var _this = this;
            var form = $('#optimize-confirm-modal');

            var ads = [];
            form.find('[name="ads.adGroup"]').each(function(i, v) {
                var adGroupId = $(this).val();
                var status = $(this).data('adgroup-status');
                ads.push({
                    adGroupId: adGroupId,
                    status: status
                });
            });
            var params = {};
            if (ads.length > 0) {
                params.ads = ads;
            }

            var id = _this.adSetData.id;
            var adSetId = _this.adSetData.adsetId;
            var fbAccountId = _this.adSetData.fbAccountId;
            var budgetType = form.find('[name="budgetType"]').val();
            var budgetOld = _this.accMul(form.find('[name="budgetOld"]').val(),100);
            var budgetNew = _this.accMul(form.find('[name="budgetNew"]').val(),100);
            var bidInfokey = form.find('[name="vpiOldKey"]').val();
            var bidInfoOld = _this.accMul(form.find('[name="vpiOld"]').val(),100);
            var bidInfoNew = _this.accMul(form.find('[name="vpiNew"]').val(),100);
            var status = form.find('[name="status"]').val();
            var isWatch = form.find('[name="isWatch"]:checked').val();
            var delayHours = form.find('[name="delayHours"]').val();
            var delaySpent = form.find('[name="delaySpent"]').val();
            var ruleId = _this.adSetData.ruleId;

            if (id && id !== '') {
                params.id = id;
            }
            if (adSetId && adSetId !== '') {
                params.adSetId = adSetId;
            }
            if (fbAccountId && fbAccountId !== '') {
                params.fbAccountId = fbAccountId;
            }
            if (budgetType && budgetType !== '') {
                params.budgetType = budgetType;
            }
            if (budgetOld && budgetOld !== '') {
                params.budgetOld = budgetOld;
            }
            if (budgetNew && budgetNew !== '') {
                params.budgetNew = budgetNew;
            }
            if (bidInfoOld && bidInfoOld !== '') {
                var p = {};
                p[bidInfokey] = bidInfoOld;
                params.bidInfoOld = JSON.stringify(p);
            }
            if (bidInfoNew && bidInfoNew !== '') {
                var pa = {};
                pa[bidInfokey] = bidInfoNew;
                params.bidInfoNew = JSON.stringify(pa);
            }
            if (status && status !== '') {
                params.status = status;
            }
            if (isWatch && isWatch !== '') {
                params.isWatch = isWatch;
            }
            if (delayHours && delayHours !== '') {
                params.delayHours = delayHours;
            }
            if (delaySpent && delaySpent !== '') {
                params.delaySpent = delaySpent;
            }
            if (ruleId && ruleId !== ''){
                params.ruleId=ruleId;
            }
            return params;
        },
        accMul: function (arg1,arg2){
            if(arg1==undefined||arg2==undefined) return  '';
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        },
        /**
         * [cleanAllSnap 清除所有快照数据]
         * @return {[type]} [description]
         */
        cleanAllSnap: function() {
            var _this = this;
            //TOTO modal
            var cleanModal= $('#clean-modal');
            cleanModal.modal({
                backdrop: 'static',
                keyboard: false
            });
            cleanModal.modal("show");

            //确认清除
            $("#clean-btn", cleanModal).off("click").on("click", function(){
                http.work('/ruleresult/cleanAllSnap',{},'POST').then(function(res){
                    Kit.alert2(I18N.getText('rulescriptResult','clearCuccess'));
                    _this.queryGroup();
                });
                cleanModal.modal("hide");
            });
        },
        /**
         * [editValue 修改数值]
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        editValue: function(e) {
            var _p;
            if ($(e.target).hasClass("edit")){
                _p =  $(e.target).parent();
            } else {
                _p =  $(e.target).parent().parent();
            }

            _p.addClass('hide');
            _p.next().removeClass('hide');
            _p.next().find(".edit-input").focus();
            return false;
        },
        modifyFocusout: function(e) {
            var value = $(e.target).val();
            $(e.target).parent().prev().find('.origin-show').text('$' + value);
            $(e.target).parent().addClass('hide');
            $(e.target).parent().prev().removeClass('hide');
        },
    };
    return RuleScriptResult;
});
